package com.foreknow.controller;

import com.foreknow.model.Admin;
import com.foreknow.service.AdminService;
import com.foreknow.service.impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据键获取值
        String uname = req.getParameter("uname");
        AdminService service = new AdminServiceImpl();
        boolean isRight = service.getName(uname);
        String data=null;
        if (isRight){
            data="<font color='green'>输入正确</font>";
            resp.getWriter().println(data);
        }else {
            data="<font color='red'>无此用户</font>";
            resp.getWriter().println(data);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        获取到请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        //调用service
        AdminService service=new AdminServiceImpl();
        //传递sql语句所需值  并且接收查询到的值
        Admin admin = service.isValidate(username, password);
        if (admin!=null){
            //将用户登录的名字保存到服务器
            session.setAttribute("username",admin.getUsername());
            //使用req请求中的方法（请求转发）去请求在xml文件中定义的访问servlet方法
//            req.getRequestDispatcher("/user/manager?q=list").forward(req,resp);
            resp.sendRedirect(req.getContextPath()+"/user/manager?q=list");
        }else{
            resp.getWriter().println("失败");
        }
    }
}
